<template>
  <div class="question-bank-container">
    <!-- 返回按钮 -->
    <div class="back-button">
      <el-button @click="handleBack" type="primary" plain>
        <el-icon><ArrowLeft /></el-icon>返回
      </el-button>
    </div>

    <!-- 左侧分类面板 -->
    <side-panel
      title="章节筛选"
      class="left-panel"
      :collapsed="leftCollapsed"
      @update:collapsed="leftCollapsed = $event"
    >
      <div class="question-bank-selector">
        <div class="selector-header">
          <el-select
            v-model="currentBankId"
            placeholder="选择试题库"
            class="bank-select"
            @change="handleBankChange"
          >
            <el-option
              v-for="bank in questionBanks"
              :key="bank.questionName"
              :label="bank.questionName"
              :value="bank.questionName"
            >
              <div class="bank-option">
                <span>{{ bank.questionName }}</span>
              </div>
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="chapter-list">
        <el-radio-group v-model="selectedChapter" @change="handleChapterChange">
          <el-radio-button label="">全部章节</el-radio-button>
          <el-radio-button 
            v-for="chapter in chapterList" 
            :key="chapter" 
            :label="chapter"
          >
            {{ chapter }}
          </el-radio-button>
        </el-radio-group>
      </div>
    </side-panel>

    <!-- 中间内容区域 -->
    <div class="main-content">
      <!-- 工具栏 -->
      <div class="toolbar">
        <div class="left-tools">
          <el-button type="primary" @click="handleAddQuestion">
            <el-icon><Plus /></el-icon>新增试题
          </el-button>
          <el-button @click="handleBatchImport">
            <el-icon><Upload /></el-icon>批量导入
          </el-button>
          <el-button @click="handleDownloadTemplate">
            <el-icon><Download /></el-icon>下载模板
          </el-button>
          <el-button @click="handleBatchDelete" :disabled="!selectedQuestions.length">
            <el-icon><Delete /></el-icon>批量删除
          </el-button>
        </div>
        <div class="right-tools">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索试题"
            class="search-input"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </div>
      </div>

      <!-- 试题列表 -->
      <div class="question-table">
        <el-table
          :data="questionList"
          @selection-change="handleSelectionChange"
          style="width: 100%"
          :empty-text="'暂无数据'"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="type" label="题型" width="120" />
          <el-table-column prop="content" label="题目内容" min-width="200" show-overflow-tooltip />
          <el-table-column prop="subject" label="所属章节" width="120" />
          <el-table-column prop="difficulty" label="难度" width="100" />
          <el-table-column prop="updateTime" label="更新时间" width="180">
            <template #default="scope">
              {{ scope.row.updateTime ? new Date(scope.row.updateTime).toLocaleString() : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button link type="primary" @click="handleView(scope.row)">
                <el-icon><View /></el-icon>查看
              </el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 右侧筛选面板 -->
    <side-panel
      title="筛选条件"
      class="right-panel"
      :collapsed="rightCollapsed"
      @update:collapsed="rightCollapsed = $event"
    >
      <div class="filter-form">
        <div class="filter-section">
          <div class="section-title">
            <el-icon><Document /></el-icon>
            <span>题型筛选</span>
          </div>
          <div class="filter-buttons">
            <el-button
              v-for="type in questionTypes"
              :key="type.value"
              :type="filterForm.type === type.value ? 'primary' : 'default'"
              @click="handleTypeSelect(type.value)"
              class="filter-btn"
            >
              {{ type.label }}
            </el-button>
          </div>
        </div>

        <div class="filter-section">
          <div class="section-title">
            <el-icon><InfoFilled /></el-icon>
            <span>难度等级</span>
          </div>
          <el-select v-model="filterForm.difficulty" placeholder="选择难度等级" class="difficulty-select">
            <el-option label="选择难度等级" value="" />
            <el-option
              v-for="level in difficultyLevels"
              :key="level.value"
              :label="level.label"
              :value="level.value"
            />
          </el-select>
        </div>

        <div class="filter-actions">
          <el-button @click="resetFilter" class="reset-button">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
      </div>
    </side-panel>

    <!-- 添加试题库管理对话框 -->
    <el-dialog
      v-model="bankManagementVisible"
      title="试题库管理"
      width="600px"
      destroy-on-close
    >
      <div class="bank-management">
        <div class="bank-list">
          <div v-for="bank in questionBanks" :key="bank.id" class="bank-item">
            <div class="bank-info">
              <div class="bank-name">{{ bank.name }}</div>
              <div class="bank-stats">
                <span>{{ bank.questionCount }}题</span>
                <span>{{ bank.createTime }}</span>
              </div>
            </div>
            <div class="bank-actions">
              <el-button link type="primary" @click="editBank(bank)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button link type="danger" @click="deleteBank(bank)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
        <div class="bank-add">
          <el-button type="primary" @click="showCreateBank">
            <el-icon><Plus /></el-icon>新建试题库
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 添加/编辑试题库对话框 -->
    <el-dialog
      v-model="bankFormVisible"
      :title="bankFormType === 'create' ? '新建试题库' : '编辑试题库'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="bankFormRef"
        :model="bankForm"
        :rules="bankRules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="bankForm.name" placeholder="请输入试题库名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="bankForm.description"
            type="textarea"
            placeholder="请输入试题库描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bankFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBankForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入试题对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="批量导入试题"
      width="500px"
      destroy-on-close
      @open="() => { console.log('对话框打开，上传组件:', uploadRef) }"
    >
      <el-form
        ref="importFormRef"
        :model="importForm"
        :rules="importRules"
        label-width="100px"
      >
        <el-form-item label="选择题库" prop="questionBank">
          <el-autocomplete
            v-model="importForm.questionBank"
            :fetch-suggestions="queryBankSearch"
            placeholder="请输入或选择题库"
            clearable
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="Excel文件">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            drag
            action="/importQuestionExcel"
            :headers="uploadHeaders"
            :data="uploadData"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :on-progress="handleUploadProgress"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            :accept="'.xlsx,.xls'"
            :show-file-list="true"
            :limit="1"
            :multiple="false"
            :auto-upload="false"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 xlsx/xls 文件，且文件大小不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitImport">开始导入</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看试题详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="试题详情"
      width="700px"
      destroy-on-close
    >
      <div v-if="currentQuestion" class="question-detail">
        <div class="detail-header">
          <div class="detail-title">
            <span class="label">题目内容：</span>
            <span class="content">{{ currentQuestion.content }}</span>
          </div>
          <div class="detail-meta">
            <el-tag>{{ currentQuestion.type }}</el-tag>
            <el-tag type="success">{{ currentQuestion.subject }}</el-tag>
            <el-tag type="warning">{{ currentQuestion.difficulty }}</el-tag>
          </div>
        </div>
        
        <div class="detail-options" v-if="currentQuestion.options && currentQuestion.options.length">
          <div class="options-title">选项：</div>
          <div class="options-list">
            <div v-for="(option, index) in currentQuestion.options" :key="index" class="option-item">
              {{ option }}
            </div>
          </div>
        </div>
        
        <div class="detail-answer">
          <div class="answer-title">正确答案：</div>
          <div class="answer-content">{{ currentQuestion.answer }}</div>
        </div>
        
        <div class="detail-analysis">
          <div class="analysis-title">解析：</div>
          <div class="analysis-content">{{ currentQuestion.analysis || '暂无解析' }}</div>
        </div>
        
        <div class="detail-footer">
          <div class="detail-info">
            <span>创建者：{{ currentQuestion.creatorId }}</span>
            <span>更新时间：{{ formatDate(currentQuestion.updateTime) }}</span>
          </div>
        </div>
      </div>
      <div v-else class="loading-placeholder">
        <el-skeleton :rows="6" animated />
      </div>
    </el-dialog>

    <!-- 编辑试题对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑试题"
      width="700px"
      destroy-on-close
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
        v-loading="editLoading"
      >
        <el-form-item label="题目内容" prop="content">
          <el-input
            v-model="editForm.content"
            type="textarea"
            :rows="3"
            placeholder="请输入题目内容"
          />
        </el-form-item>
        
        <el-form-item label="题型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择题型">
            <el-option
              v-for="type in questionTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="所属章节" prop="subject">
          <el-input
            v-model="editForm.subject"
            placeholder="请输入所属章节，如：第一章"
          />
        </el-form-item>
        
        <el-form-item label="难度" prop="difficulty">
          <el-select v-model="editForm.difficulty" placeholder="请选择难度">
            <el-option label="易" value="易" />
            <el-option label="偏易" value="偏易" />
            <el-option label="适中" value="适中" />
            <el-option label="偏难" value="偏难" />
            <el-option label="难" value="难" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="选项" v-if="['单选题', '多选题'].includes(editForm.type)">
          <div v-for="(option, index) in editForm.options" :key="index" class="option-item">
            <el-input v-model="editForm.options[index]" placeholder="请输入选项内容">
              <template #prepend>{{ String.fromCharCode(65 + index) }}:</template>
              <template #append>
                <el-button @click="removeOption(index)" :disabled="editForm.options.length <= 2">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
          <div class="add-option">
            <el-button type="primary" @click="addOption" :disabled="editForm.options.length >= 10">
              <el-icon><Plus /></el-icon>添加选项
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="正确答案" prop="answer">
          <el-input
            v-if="['单选题', '多选题'].includes(editForm.type)"
            v-model="editForm.answer"
            placeholder="请输入正确答案，如：A,B,C"
          />
          <el-input
            v-else
            v-model="editForm.answer"
            type="textarea"
            :rows="3"
            placeholder="请输入正确答案"
          />
        </el-form-item>
        
        <el-form-item label="解析" prop="analysis">
          <el-input
            v-model="editForm.analysis"
            type="textarea"
            :rows="3"
            placeholder="请输入题目解析"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增试题对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增试题"
      width="700px"
      destroy-on-close
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="选择题库" prop="questionName">
          <el-select v-model="addForm.questionName" placeholder="请选择题库">
            <el-option
              v-for="bank in questionBanks"
              :key="bank.questionName"
              :label="bank.questionName"
              :value="bank.questionName"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="题目内容" prop="content">
          <el-input
            v-model="addForm.content"
            type="textarea"
            :rows="3"
            placeholder="请输入题目内容"
          />
        </el-form-item>
        
        <el-form-item label="题型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择题型">
            <el-option
              v-for="type in questionTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="所属章节" prop="subject">
          <el-input
            v-model="addForm.subject"
            placeholder="请输入所属章节，如：第一章"
          />
        </el-form-item>
        
        <el-form-item label="难度" prop="difficulty">
          <el-select v-model="addForm.difficulty" placeholder="请选择难度">
            <el-option label="易" value="易" />
            <el-option label="偏易" value="偏易" />
            <el-option label="适中" value="适中" />
            <el-option label="偏难" value="偏难" />
            <el-option label="难" value="难" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="选项" v-if="['单选题', '多选题'].includes(addForm.type)">
          <div v-for="(option, index) in addForm.options" :key="index" class="option-item">
            <el-input v-model="addForm.options[index]" placeholder="请输入选项内容">
              <template #prepend>{{ String.fromCharCode(65 + index) }}:</template>
              <template #append>
                <el-button @click="removeAddOption(index)" :disabled="addForm.options.length <= 2">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
          <div class="add-option">
            <el-button type="primary" @click="addOption" :disabled="addForm.options.length >= 10">
              <el-icon><Plus /></el-icon>添加选项
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="正确答案" prop="answer">
          <el-input
            v-if="['单选题', '多选题'].includes(addForm.type)"
            v-model="addForm.answer"
            placeholder="请输入正确答案，如：A,B,C"
          />
          <el-input
            v-else
            v-model="addForm.answer"
            type="textarea"
            :rows="3"
            placeholder="请输入正确答案"
          />
        </el-form-item>
        
        <el-form-item label="解析" prop="analysis">
          <el-input
            v-model="addForm.analysis"
            type="textarea"
            :rows="3"
            placeholder="请输入题目解析"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import SidePanel from '@/components/SidePanel.vue'
import {
  Plus,
  Upload,
  Delete,
  Search,
  Refresh,
  Edit,
  View,
  ArrowDown,
  ArrowUp,
  List,
  Warning,
  Calendar,
  Star,
  CircleCheck,
  Setting,
  UploadFilled,
  Document,
  InfoFilled,
  Download,
  ArrowLeft
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'
import request from '@/utils/request'

// 控制面板展开/收起状态
const leftCollapsed = ref(false)
const rightCollapsed = ref(false)
const router = useRouter()

// 章节相关
const selectedChapter = ref('')
const chapterList = ref([])

// 原始数据存储
const originalQuestions = ref([])

// 添加中文数字转换函数
const chineseToNumber = (chinese) => {
  const chineseNumbers = {
    '一': 1, '二': 2, '三': 3, '四': 4, '五': 5,
    '六': 6, '七': 7, '八': 8, '九': 9, '十': 10
  }
  return chineseNumbers[chinese] || 0
}

// 修改 extractChapters 函数
const extractChapters = (questions) => {
  if (!questions || !Array.isArray(questions)) return
  
  const chapters = new Set()
  questions.forEach(question => {
    if (question.subject) {
      chapters.add(question.subject)
    }
  })
  
  // 将 Set 转换为数组并排序
  chapterList.value = Array.from(chapters).sort((a, b) => {
    // 提取中文数字并转换为阿拉伯数字
    const numA = chineseToNumber(a.match(/第(.*?)章/)?.[1] || '')
    const numB = chineseToNumber(b.match(/第(.*?)章/)?.[1] || '')
    return numA - numB
  })
  
  console.log('提取的章节列表:', chapterList.value)  // 添加日志
}

// 修改难度等级选项的定义
const difficultyLevels = computed(() => {
  if (!questionList.value || !questionList.value.length) return []
  
  // 从题目中提取所有不同的难度等级
  const difficultySet = new Set(questionList.value.map(q => q.difficulty))
  
  // 转换为选项数组格式
  return Array.from(difficultySet)
    .filter(difficulty => difficulty) // 过滤掉可能的 null 或 undefined
    .map(difficulty => ({
      value: difficulty,
      label: difficulty
    }))
    .sort((a, b) => {
      // 定义难度等级的排序权重
      const weights = {
        '易': 1,
        '偏易': 2,
        '适中': 3,
        '偏难': 4,
        '难': 5
      }
      return (weights[a.value] || 0) - (weights[b.value] || 0)
    })
})

// 修改 fetchQuestionData 方法，确保返回的数据包含 questionId
const fetchQuestionData = async () => {
  try {
    const response = await request.get('/nerv/selectQuestion', {
      params: {
        question_name: currentBankId.value,
        type: filterForm.type,
        difficulty: filterForm.difficulty,
        subject: filterForm.subject,
        keyword: searchKeyword.value,
        page: currentPage.value,
        size: pageSize.value
      }
    })
    if (response.code === 200) {
      const data = response.data
      // 确保每条数据都有 questionId
      questionList.value = data.records.map(item => ({
        ...item,
        questionId: item.questionId // 确保 questionId 字段存在
      }))
      total.value = data.total
      
      // 从题目数据中提取章节列表
      extractChapters(data.records)
    }
  } catch (error) {
    console.error('获取题目数据失败:', error)
    ElMessage.error('获取题目数据失败')
  }
}

// 修改章节选择处理函数
const handleChapterChange = (chapter) => {
  filterForm.subject = chapter
  currentPage.value = 1  // 重置页码
  fetchQuestionData()    // 重新获取数据
}

// 搜索关键词
const searchKeyword = ref('')

// 筛选表单
const filterForm = reactive({
  type: '',
  difficulty: '',
  subject: ''
})

// 监听筛选条件变化
watch(filterForm, () => {
  // 重置分页到第一页
  currentPage.value = 1
  // 重新获取数据
  fetchQuestionData()
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 选中的试题
const selectedQuestions = ref([])

// 试题列表数据
const questionList = ref([
  {
    question_name: '示例试题1',
    type: '单选题',
    subject: '第一章',
    difficulty: '适中',
    creator_id: '张老师',
    create_time: '2024-03-15 10:00:00'
  },
  // ... 更多示例数据
])

// 试题库相关
const currentBankId = ref('')
const questionBanks = ref([])

// 试题库管理对话框
const bankManagementVisible = ref(false)
const bankFormVisible = ref(false)
const bankFormType = ref('create')
const bankFormRef = ref(null)
const bankForm = reactive({
  name: '',
  description: ''
})

const bankRules = {
  name: [
    { required: true, message: '请输入试题库名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '不能超过200个字符', trigger: 'blur' }
  ]
}

// 导入对话框相关
const importDialogVisible = ref(false)
const importFormRef = ref(null)
const importForm = reactive({
  questionBank: '',
  file: null
})

// 题库搜索建议
const queryBankSearch = (queryString, cb) => {
  const results = queryString
    ? questionBanks.value.filter(bank => 
        bank.questionName.toLowerCase().includes(queryString.toLowerCase())
      )
    : questionBanks.value
  
  cb(results)
}

// 修改导入表单验证规则
const importRules = {
  questionBank: [
    { required: true, message: '请输入或选择题库', trigger: 'blur' }
  ]
}

// 上传相关配置
const uploadRef = ref(null)
const uploadHeaders = computed(() => ({
  'Authorization': sessionStorage.getItem('token')
}))

const uploadData = computed(() => ({
  questionName: importForm.questionBank
}))

// 添加文件列表状态
const fileList = ref([])

// 文件选择改变事件
const handleFileChange = (uploadFile, uploadFiles) => {
  console.log('文件选择改变:', uploadFile, uploadFiles)
  fileList.value = [...uploadFiles]
  console.log('更新后的文件列表:', fileList.value)
}

// 文件移除事件
const handleFileRemove = (uploadFile, uploadFiles) => {
  console.log('文件被移除:', uploadFile, uploadFiles)
  fileList.value = [...uploadFiles]
  console.log('更新后的文件列表:', fileList.value)
}

// 修改提交导入方法
const submitImport = async () => {
  console.log('开始提交导入')
  console.log('当前题库名称:', importForm.questionBank)
  console.log('上传组件引用:', uploadRef.value)
  console.log('当前文件列表:', fileList.value)
  
  if (!importForm.questionBank) {
    ElMessage.warning('请先输入或选择题库')
    return
  }

  // 确保上传组件已经初始化
  if (!uploadRef.value) {
    console.error('上传组件未初始化')
    ElMessage.error('系统错误：上传组件未初始化')
    return
  }

  // 检查是否有选择文件
  if (!fileList.value || fileList.value.length === 0) {
    ElMessage.warning('请选择要上传的Excel文件')
    return
  }

  try {
    const formData = new FormData()
    formData.append('excelFile', fileList.value[0].raw)
    formData.append('questionName', importForm.questionBank)
    
    // 从sessionStorage获取用户信息
    const userInfoStr = sessionStorage.getItem('userInfo')
    if (!userInfoStr) {
      ElMessage.error('未获取到用户信息，请重新登录')
      router.push('/login')
      return
    }
    const userInfo = JSON.parse(userInfoStr)
    formData.append('creatorId', userInfo.schoolNumber)  // 添加creatorId参数

    const response = await request({
      url: '/importQuestionExcel',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.code === 200) {
      ElMessage.success('试题导入成功')
      importDialogVisible.value = false
      // 重置表单和上传组件
      importForm.questionBank = ''
      fileList.value = []
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
      // 刷新试题列表
      fetchQuestionData()
    } else {
      ElMessage.error(response.message || '导入失败')
    }
  } catch (error) {
    console.error('提交上传失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response)
      if (error.response.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        router.push('/login')
      } else if (error.response.status === 404) {
        ElMessage.error('上传接口不存在，请检查服务器配置')
      } else {
        ElMessage.error(error.response.data?.message || '文件上传失败')
      }
    } else {
      ElMessage.error('提交失败，请重试')
    }
  }
}

// 监听导入对话框的打开，重置表单和上传组件
watch(importDialogVisible, (val) => {
  if (val) {
    // 对话框打开时重置
    importForm.questionBank = ''
    fileList.value = []
    if (uploadRef.value) {
      uploadRef.value.clearFiles()
    }
    console.log('导入对话框打开，重置状态')
    console.log('文件列表:', fileList.value)
  }
})

// 上传前验证
const beforeUpload = (file) => {
  console.log('开始验证文件:', file.name)
  console.log('文件类型:', file.type)
  console.log('文件大小:', file.size)

  // 检查文件扩展名
  const fileName = file.name.toLowerCase()
  const isExcelExt = fileName.endsWith('.xlsx') || fileName.endsWith('.xls')
  console.log('文件扩展名检查:', isExcelExt)

  if (!isExcelExt) {
    ElMessage.error('请上传 .xlsx 或 .xls 格式的Excel文件!')
    return false
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10
  console.log('文件大小检查:', isLt10M)

  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  
  return true
}

// 修改上传成功处理函数
const handleUploadSuccess = (response, uploadFile) => {
  console.log('上传成功，响应数据:', response)
  console.log('上传的文件信息:', uploadFile)
  
  if (response.code === 200) {
    ElMessage.success('试题导入成功')
    importDialogVisible.value = false
    // 重置表单和上传组件
    importForm.questionBank = ''
    fileList.value = []
    if (uploadRef.value) {
      uploadRef.value.clearFiles()
    }
    // 刷新试题列表
    fetchQuestionData()
  } else {
    ElMessage.error(response.message || '导入失败')
    // 上传失败时，保留文件在列表中
    uploadFile.status = 'ready'
  }
}

// 修改上传错误处理函数
const handleUploadError = (error, uploadFile) => {
  console.error('上传失败:', error)
  console.error('失败的文件信息:', uploadFile)
  
  if (error.response) {
    console.error('错误响应:', error.response)
    if (error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
    } else if (error.response.status === 404) {
      ElMessage.error('上传接口不存在，请检查服务器配置')
    } else {
      ElMessage.error(error.response.data?.message || '文件上传失败')
    }
  } else if (error.message) {
    ElMessage.error(`上传失败: ${error.message}`)
  } else {
    ElMessage.error('文件上传失败，请重试')
  }
}

// 上传进度处理
const handleUploadProgress = (event, file) => {
  console.log('上传进度:', event.percent)
  if (event.percent === 100) {
    console.log('文件上传完成，等待服务器响应')
  }
}

// 新增试题相关
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
  questionName: '',
  content: '',
  type: '',
  subject: '',
  difficulty: '',
  options: ['', ''],
  answer: '',
  analysis: ''
})

const addRules = {
  questionName: [
    { required: true, message: '请选择题库', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入题目内容', trigger: 'blur' },
    { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择题型', trigger: 'change' }
  ],
  subject: [
    { required: true, message: '请输入所属章节', trigger: 'blur' }
  ],
  difficulty: [
    { required: true, message: '请选择难度', trigger: 'change' }
  ],
  answer: [
    { required: true, message: '请输入正确答案', trigger: 'blur' }
  ]
}

// 添加选项
const addOption = () => {
  if (addForm.options.length < 10) {
    addForm.options.push('')
  }
}

// 移除选项
const removeAddOption = (index) => {
  if (addForm.options.length > 2) {
    addForm.options.splice(index, 1)
    // 更新答案，移除被删除的选项
    if (['单选题', '多选题'].includes(addForm.type)) {
      const answerArray = addForm.answer.split(',')
      const newAnswerArray = answerArray.filter(a => {
        const optionIndex = a.charCodeAt(0) - 65
        return optionIndex !== index
      })
      addForm.answer = newAnswerArray.join(',')
    }
  }
}

// 处理新增试题
const handleAddQuestion = () => {
  addDialogVisible.value = true
  // 重置表单
  addForm.questionName = currentBankId.value // 设置当前选中的题库
  addForm.content = ''
  addForm.type = ''
  addForm.subject = ''
  addForm.difficulty = ''
  addForm.options = ['', '']
  addForm.answer = ''
  addForm.analysis = ''
}

// 处理批量导入
const handleBatchImport = () => {
  importDialogVisible.value = true
  // 重置表单
  importForm.questionBank = currentBankId.value
  fileList.value = []
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 提交新增试题
const submitAdd = async () => {
  if (!addFormRef.value) return
  
  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 从sessionStorage获取用户信息
        const userInfoStr = sessionStorage.getItem('userInfo')
        if (!userInfoStr) {
          ElMessage.error('未获取到用户信息，请重新登录')
          router.push('/login')
          return
        }
        const userInfo = JSON.parse(userInfoStr)
        
        // 准备提交的数据
        const submitData = {
          creatorId: userInfo.schoolNumber,
          questionName: addForm.questionName, // 使用表单中选择的题库
          content: addForm.content,
          type: addForm.type,
          subject: addForm.subject,
          difficulty: addForm.difficulty,
          answer: addForm.answer,
          analysis: addForm.analysis
        }
        
        // 如果是选择题，处理选项
        if (['单选题', '多选题'].includes(addForm.type)) {
          submitData.options = addForm.options.map((opt, index) => {
            return `${String.fromCharCode(65 + index)}:${opt}`
          })
        }
        
        console.log('提交的新增试题数据:', submitData)
        
        // 发送新增请求
        const response = await request({
          url: '/importQuestion',
          method: 'post',
          data: submitData
        })
        
        if (response.code === 200) {
          ElMessage.success(response.message || '新增成功')
          addDialogVisible.value = false
          // 重新加载数据
          fetchQuestionData()
        } else {
          ElMessage.error(response.message || '新增失败')
        }
      } catch (error) {
        console.error('新增试题失败:', error)
        if (error.response) {
          console.error('错误响应:', error.response)
          if (error.response.status === 401) {
            ElMessage.error('登录已过期，请重新登录')
            router.push('/login')
          } else {
            ElMessage.error(error.response.data?.message || '新增失败')
          }
        } else if (error.request) {
          console.error('请求未收到响应')
          ElMessage.error('服务器未响应，请检查网络连接')
        } else {
          console.error('请求配置错误:', error.message)
          ElMessage.error('请求配置错误')
        }
      }
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

// 处理编辑
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editLoading = ref(false)
const editForm = reactive({
  questionId: '',
  content: '',
  type: '',
  subject: '',
  difficulty: '',
  options: ['', ''],
  answer: '',
  analysis: ''
})

const editRules = {
  content: [
    { required: true, message: '请输入题目内容', trigger: 'blur' },
    { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择题型', trigger: 'change' }
  ],
  subject: [
    { required: true, message: '请选择所属章节', trigger: 'change' }
  ],
  difficulty: [
    { required: true, message: '请选择难度', trigger: 'change' }
  ],
  answer: [
    { required: true, message: '请输入正确答案', trigger: 'blur' }
  ]
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    console.log('编辑试题:', row)
    editDialogVisible.value = true
    editLoading.value = true
    
    // 获取试题详情
    const response = await request({
      url: '/selectQuestion_id',
      method: 'get',
      params: {
        question_id: row.questionId
      }
    })
    
    if (response.code === 200) {
      const questionData = response.data
      console.log('获取到的试题详情:', questionData)
      
      // 填充表单数据
      editForm.questionId = questionData.questionId
      editForm.content = questionData.content
      editForm.type = questionData.type
      editForm.subject = questionData.subject
      editForm.difficulty = questionData.difficulty
      editForm.answer = questionData.answer
      editForm.analysis = questionData.analysis || ''
      
      // 处理选项
      if (questionData.options && questionData.options.length > 0) {
        editForm.options = questionData.options.map(opt => {
          // 移除选项前缀，如 "A:" 或 "A. "
          return opt.replace(/^[A-Z][:\.]\s*/, '')
        })
      } else {
        // 默认选项
        editForm.options = ['', '']
      }
      
      editLoading.value = false
    } else {
      ElMessage.error(response.message || '获取试题详情失败')
      editDialogVisible.value = false
    }
  } catch (error) {
    console.error('获取试题详情失败:', error)
    editLoading.value = false
    if (error.response) {
      console.error('错误响应:', error.response)
      if (error.response.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        router.push('/login')
      } else {
        ElMessage.error(error.response.data?.message || '获取试题详情失败')
      }
    } else if (error.request) {
      console.error('请求未收到响应')
      ElMessage.error('服务器未响应，请检查网络连接')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error('请求配置错误')
    }
    editDialogVisible.value = false
  }
}

// 提交编辑
const submitEdit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        editLoading.value = true
        
        // 准备提交的数据
        const submitData = {
          questionId: editForm.questionId,
          content: editForm.content,
          type: editForm.type,
          subject: editForm.subject,
          difficulty: editForm.difficulty,
          answer: editForm.answer,
          analysis: editForm.analysis
        }
        
        // 如果是选择题，处理选项
        if (['单选题', '多选题'].includes(editForm.type)) {
          submitData.options = editForm.options.map((opt, index) => {
            return `${String.fromCharCode(65 + index)}:${opt}`
          })
        }
        
        console.log('提交的编辑数据:', submitData)
        
        // 发送更新请求
        const response = await request({
          url: '/updateQuestion',
          method: 'post',
          data: submitData
        })
        
        if (response.code === 200) {
          ElMessage.success(response.message || '更新成功')
          editDialogVisible.value = false
          // 重新加载数据
          fetchQuestionData()
        } else {
          ElMessage.error(response.message || '更新失败')
        }
      } catch (error) {
        console.error('更新试题失败:', error)
        if (error.response) {
          console.error('错误响应:', error.response)
          if (error.response.status === 401) {
            ElMessage.error('登录已过期，请重新登录')
            router.push('/login')
          } else {
            ElMessage.error(error.response.data?.message || '更新失败')
          }
        } else if (error.request) {
          console.error('请求未收到响应')
          ElMessage.error('服务器未响应，请检查网络连接')
        } else {
          console.error('请求配置错误:', error.message)
          ElMessage.error('请求配置错误')
        }
      } finally {
        editLoading.value = false
      }
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

// 查看试题对话框
const viewDialogVisible = ref(false)
const currentQuestion = ref(null)

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 处理查看
const handleView = async (row) => {
  try {
    console.log('查看试题:', row)
    viewDialogVisible.value = true
    currentQuestion.value = null // 清空当前试题，显示加载状态
    
    const response = await request({
      url: '/selectQuestion_id',
      method: 'get',
      params: {
        question_id: row.questionId
      }
    })
    
    if (response.code === 200) {
      currentQuestion.value = response.data
      console.log('获取到的试题详情:', currentQuestion.value)
    } else {
      ElMessage.error(response.message || '获取试题详情失败')
    }
  } catch (error) {
    console.error('获取试题详情失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response)
      if (error.response.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        router.push('/login')
      } else {
        ElMessage.error(error.response.data?.message || '获取试题详情失败')
      }
    } else if (error.request) {
      console.error('请求未收到响应')
      ElMessage.error('服务器未响应，请检查网络连接')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error('请求配置错误')
    }
  }
}

// 修改单个删除方法
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这道试题吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await request({
        url: '/deleteQuestion',
        method: 'delete',
        params: {
          question_id: row.questionId
        }
      })
      
      if (response.code === 200) {
        ElMessage.success(response.message || '删除成功')
        // 重新加载数据
        fetchQuestionData()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      if (error.response) {
        console.error('错误响应:', error.response)
        if (error.response.status === 401) {
          ElMessage.error('登录已过期，请重新登录')
          router.push('/login')
        } else {
          ElMessage.error(error.response.data?.message || '删除失败')
        }
      } else if (error.request) {
        console.error('请求未收到响应')
        ElMessage.error('服务器未响应，请检查网络连接')
      } else {
        console.error('请求配置错误:', error.message)
        ElMessage.error('请求配置错误')
      }
    }
  }).catch(() => {
    // 取消删除，不做任何操作
  })
}

// 重置筛选
const resetFilter = () => {
  filterForm.type = ''
  filterForm.difficulty = ''
  filterForm.subject = ''
  selectedChapter.value = ''
  currentPage.value = 1
  fetchQuestionData()
}

// 题型选项
const questionTypes = [
  { value: '单选题', label: '单选题' },
  { value: '多选题', label: '多选题' },
  { value: '判断题', label: '判断题' },
  { value: '填空题', label: '填空题' },
  { value: '问答题', label: '问答题' }
]

// 处理题型选择
const handleTypeSelect = (type) => {
  if (filterForm.type === type) {
    filterForm.type = ''
  } else {
    filterForm.type = type
  }
}

// 切换试题库
const handleBankChange = (bankName) => {
  currentBankId.value = bankName
  resetFilter()
}

// 显示试题库管理
const showBankManagement = () => {
  bankManagementVisible.value = true
}

// 显示创建试题库表单
const showCreateBank = () => {
  bankFormType.value = 'create'
  bankForm.name = ''
  bankForm.description = ''
  bankFormVisible.value = true
}

// 编辑试题库
const editBank = (bank) => {
  bankFormType.value = 'edit'
  bankForm.name = bank.name
  bankForm.description = bank.description || ''
  bankFormVisible.value = true
}

// 删除试题库
const deleteBank = (bank) => {
  ElMessageBox.confirm(
    `确定要删除试题库"${bank.name}"吗？删除后不可恢复。`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 调用删除API
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 提交试题库表单
const submitBankForm = async () => {
  if (!bankFormRef.value) return
  await bankFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 调用创建/编辑API
      ElMessage.success(bankFormType.value === 'create' ? '创建成功' : '修改成功')
      bankFormVisible.value = false
      // 刷新试题库列表
    }
  })
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchQuestionData()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchQuestionData()
}

// 加载试题库列表
const loadQuestionBanks = async () => {
  try {
    const userInfoStr = sessionStorage.getItem('userInfo')
    console.log('获取到的userInfo:', userInfoStr)
    
    let schoolNumber = null
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr)
      schoolNumber = userInfo.schoolNumber
    }
    console.log('解析得到的schoolNumber:', schoolNumber)
    
    if (!schoolNumber) {
      console.log('schoolNumber为空，准备跳转到登录页')
      ElMessage.error('未获取到用户信息，请重新登录')
      router.push('/login')
      return
    }
    
    console.log('正在请求试题库列表，用户ID:', schoolNumber)
    const response = await axios.get('http://localhost:8080/showExam', {
      params: {
        schoolNumber: schoolNumber
      },
      headers: {
        'Authorization': sessionStorage.getItem('token')
      }
    })
    console.log('试题库列表响应:', response)
    
    if (response.data.code === 200) {
      questionBanks.value = response.data.data
      if (questionBanks.value.length > 0) {
        currentBankId.value = questionBanks.value[0].questionName
        fetchQuestionData()
      }
    } else {
      ElMessage.error(response.data.message || '获取试题库列表失败')
    }
  } catch (error) {
    console.error('加载试题库失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      ElMessage.error(`加载试题库失败: ${error.response.data.message || '未知错误'}`)
    } else if (error.request) {
      console.error('请求未收到响应')
      ElMessage.error('服务器未响应，请检查网络连接')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error('请求配置错误')
    }
  }
}

// 在组件挂载时加载试题库列表
onMounted(() => {
  console.log('组件挂载，准备加载试题库列表')
  loadQuestionBanks()
})

// 处理下载模板
const handleDownloadTemplate = () => {
  // 创建一个a标签用于下载
  const link = document.createElement('a')
  link.href = '/批量导入试题模板.xlsx'
  link.download = '批量导入试题模板.xlsx'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('模板下载请求已发送')
}

// 处理返回
const handleBack = () => {
  router.back()
}
</script>

<style scoped>
.question-bank-container {
  display: flex;
  height: 100vh;
  background-color: #f5f7fa;
  position: relative;
  padding-top: 60px; /* 为返回按钮留出空间 */
}

.left-panel, .right-panel {
  position: relative;
  background-color: #fff;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.left-panel {
  width: 250px;
  border-right: 1px solid #e6e6e6;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.right-panel {
  width: 300px;
  border-left: 1px solid #e6e6e6;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.left-panel.collapsed {
  width: 48px;
}

.right-panel.collapsed {
  width: 48px;
}

.panel-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  opacity: 1;
  transition: opacity 0.3s;
}

.collapsed .panel-content {
  opacity: 0;
  pointer-events: none;
}

.panel-header {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  border-bottom: 1px solid #e6e6e6;
  background-color: #f8f9fa;
}

.collapsed-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 16px;
  background: linear-gradient(to bottom, #f8f9fa, #ffffff);
  gap: 12px;
}

.collapsed-text {
  writing-mode: vertical-lr;
  text-orientation: upright;
  letter-spacing: 4px;
  color: #409EFF;
  font-size: 14px;
  font-weight: 500;
  padding: 12px 0;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.collapse-trigger {
  position: absolute;
  top: 50%;
  width: 20px;
  height: 50px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 0 4px 4px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transform: translateY(-50%);
  transition: all 0.3s;
  z-index: 10;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}

.collapse-trigger:hover {
  background-color: #f0f7ff;
  border-color: #409EFF;
}

.collapse-trigger.collapsed {
  border-radius: 4px;
  width: 24px;
  height: 64px;
}

.collapse-trigger.right {
  right: -20px;
  border-radius: 4px 0 0 4px;
}

.collapse-trigger.right.collapsed {
  right: -24px;
}

.left-panel .collapse-trigger {
  right: -20px;
}

.left-panel.collapsed .collapse-trigger {
  right: -24px;
}

.collapse-icon {
  font-size: 14px;
  color: #909399;
  transition: all 0.3s;
}

.collapse-trigger:hover .collapse-icon {
  color: #409EFF;
}

.chapter-list {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.chapter-list .el-radio-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.chapter-list .el-radio-button {
  margin-bottom: 8px;
}

:deep(.el-radio-button__inner) {
  width: 100%;
  text-align: left;
  border-radius: 4px !important;
  border: 1px solid #dcdfe6 !important;
  margin-bottom: 4px;
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 4px !important;
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 4px !important;
}

.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.left-tools, .right-tools {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.question-table {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: flex-end;
}

.filter-form {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.filter-section {
  margin-bottom: 24px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  color: #303133;
  font-weight: 500;
}

.section-title .el-icon {
  margin-right: 8px;
  font-size: 18px;
  color: #409EFF;
}

.filter-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 12px;
}

.filter-btn {
  flex: 1 1 calc(33.33% - 8px);
  min-width: 80px;
  margin: 0;
}

.difficulty-select {
  width: 100%;
  margin-top: 12px;
}

.filter-actions {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.filter-actions .el-button {
  width: 100%;
}

.collapse-button {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  padding: 8px 12px;
  border-radius: 4px;
  transition: all 0.3s;
}

.collapse-button:hover {
  background-color: #ecf5ff;
  color: #409EFF;
}

.collapse-button .el-icon {
  font-size: 16px;
  transition: transform 0.3s;
}

.expand-button {
  writing-mode: vertical-lr;
  text-orientation: upright;
  padding: 12px 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #409EFF;
  border-radius: 4px;
  transition: all 0.3s;
}

.expand-button:hover {
  background-color: #ecf5ff;
}

.expand-button .el-icon {
  transform: rotate(0deg);
  font-size: 16px;
}

.question-bank-selector {
  padding: 16px;
  border-bottom: 1px solid #e6e6e6;
  background-color: #f8f9fa;
}

.selector-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.bank-select {
  flex: 1;
}

.bank-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.bank-info {
  color: #909399;
  font-size: 12px;
}

.manage-bank-btn {
  padding: 8px;
}

.bank-management {
  max-height: 500px;
  overflow-y: auto;
}

.bank-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.bank-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  transition: all 0.3s;
}

.bank-item:hover {
  background-color: #ecf5ff;
}

.bank-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.bank-stats {
  font-size: 12px;
  color: #909399;
  display: flex;
  gap: 12px;
}

.bank-actions {
  display: flex;
  gap: 8px;
}

.bank-add {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

:deep(.el-select) {
  width: 100%;
}

/* 自定义滚动条 */
.bank-management::-webkit-scrollbar {
  width: 4px;
}

.bank-management::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 2px;
}

.bank-management::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 2px;
}

.upload-demo {
  width: 100%;
}

.w-full {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

:deep(.el-upload__tip) {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}

/* 试题详情样式 */
.question-detail {
  padding: 10px;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  line-height: 1.5;
}

.detail-meta {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.detail-options, .detail-answer, .detail-analysis {
  margin-bottom: 20px;
}

.options-title, .answer-title, .analysis-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #606266;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item {
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.answer-content {
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
  color: #67c23a;
}

.analysis-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
}

.detail-footer {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.detail-info {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 14px;
}

.loading-placeholder {
  padding: 20px;
}

/* 编辑试题样式 */
.option-item {
  margin-bottom: 10px;
}

.add-option {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

/* 题库建议项样式 */
.bank-suggestion {
  display: flex;
  align-items: center;
  padding: 4px 0;
}

.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 100;
}
</style> 